<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>设计模式-策略模式 | mozihao</title><meta name="keywords" content="策略模式"><meta name="author" content="mozihao"><meta name="copyright" content="mozihao"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="策略模式定义：定义一系列的算法，把他们封装起来，并且使他们可以相互替换 真人真事：大型车祸现场自我检讨一下，这是我翻了一下我以前在项目写的一段垃圾代码，是使用适当的单位来换算出带单位的文件大小，下面套用了几个if else的语句，可读性差，不美观，不利于扩展，看了想打人！！！ 123456789fileSizeFilter(size) &amp;#123;   if (size &lt; 1024) &amp;#">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式-策略模式">
<meta property="og:url" content="https://mo_zi_hao.gitee.io/blog/posts/7457/index.html">
<meta property="og:site_name" content="mozihao">
<meta property="og:description" content="策略模式定义：定义一系列的算法，把他们封装起来，并且使他们可以相互替换 真人真事：大型车祸现场自我检讨一下，这是我翻了一下我以前在项目写的一段垃圾代码，是使用适当的单位来换算出带单位的文件大小，下面套用了几个if else的语句，可读性差，不美观，不利于扩展，看了想打人！！！ 123456789fileSizeFilter(size) &amp;#123;   if (size &lt; 1024) &amp;#">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/0.png">
<meta property="article:published_time" content="2021-03-26T06:18:57.000Z">
<meta property="article:modified_time" content="2021-08-29T15:22:14.653Z">
<meta property="article:author" content="mozihao">
<meta property="article:tag" content="策略模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/0.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://mo_zi_hao.gitee.io/blog/posts/7457/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-08-29 23:22:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><link rel="stylesheet" type="text/css" href="./css/iconfont.css" media="all"><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/blog/atom.xml" title="mozihao" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC008.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">24</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 前端知识思维导图</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/mo_zi_hao/picsBed/raw/master/image/0.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">mozihao</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 前端知识思维导图</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">设计模式-策略模式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-03-26T06:18:57.000Z" title="发表于 2021-03-26 14:18:57">2021-03-26</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T15:22:14.653Z" title="更新于 2021-08-29 23:22:14">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="设计模式-策略模式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="策略模式"><a href="#策略模式" class="headerlink" title="策略模式"></a>策略模式</h1><p><strong>定义：</strong><font color="#dd0000">定义一系列的算法，把他们封装起来，并且使他们可以相互替换</font></p>
<h2 id="真人真事：大型车祸现场"><a href="#真人真事：大型车祸现场" class="headerlink" title="真人真事：大型车祸现场"></a><font color="#dd0000">真人真事：大型车祸现场</font></h2><p><font color="#dd0000">自我检讨一下，</font>这是我翻了一下我以前在项目写的一段垃圾代码，<font color="#dd0000">是使用适当的单位来换算出带单位的文件大小</font>，下面套用了几个if else的语句，<font color="#dd0000">可读性差，不美观，不利于扩展，看了想打人！！！</font></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">fileSizeFilter</span>(<span class="params">size</span>)</span> &#123;</span><br><span class="line">   <span class="keyword">if</span> (size &lt; <span class="number">1024</span>) &#123;</span><br><span class="line">       <span class="keyword">return</span> size + <span class="string">&#x27;B&#x27;</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (size / <span class="number">1024</span> &lt; <span class="number">1024</span>) &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;(size % <span class="number">1024</span>) ? (size <span class="regexp">/ 1024 ).toFixed(2) : (size /</span> <span class="number">1024</span>)&#125;</span>KB`</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;((size <span class="regexp">/ 1024) % 1024) ? (size /</span> <span class="number">1024</span> <span class="regexp">/ 1024 ).toFixed(2) : (size /</span> <span class="number">1024</span> / <span class="number">1024</span>)&#125;</span>M`</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<p><font color="#dd0000">需求：</font>由于返回的数据是以B为单位的一个number类型的数字，将这串数字用适当的单位表示，有小数点则保留两位小数    </p>
<p>如：返回1024    期望结果1KB ；  返回2000000   期望结果1.91M</p>
<p><font color="#dd0000">上面的代码逻辑：</font></p>
<p>if语句判断数据大小,区分出需要运用什么大小类型的单位,然后在通过计算返回对应单位的数值的大小</p>
<h3 id="策略模式重构代码："><a href="#策略模式重构代码：" class="headerlink" title="策略模式重构代码："></a><strong><font color="#dd0000">策略模式重构代码：</font></strong></h3><p><font color="#dd0000">策略模式的目的就是将算法的使用与算法的实现分离开来。</font></p>
<p>下面我们使用策略模式重构我的代码,将各算法封装到一个个函数里面,为了提高我们代码的可复用性，我们把这个函数放在工具类里,可以复用在程序的其他地方</p>
<h4 id="逻辑拆分："><a href="#逻辑拆分：" class="headerlink" title="逻辑拆分："></a><strong><font color="#dd0000">逻辑拆分：</font></strong></h4><ol>
<li>类型判断</li>
<li>对应类型的数据计算</li>
</ol>
<h4 id="一个基于策略模式的程序至少由两部分组成："><a href="#一个基于策略模式的程序至少由两部分组成：" class="headerlink" title="一个基于策略模式的程序至少由两部分组成："></a><strong>一个基于策略模式的程序<font color="#dd0000">至少由两部分组成：</font></strong></h4><p>1.第一部分是一组<font color="#dd0000">策略类</font>：策略类封装了具体的算法，并负责具体的计算过程</p>
<p>2.第二部分是<font color="#dd0000">环境类Context</font>：Context接受客户的请求，随后把请求委托给某一个策略类</p>
<p>说明Context中要维持对某个策略对象的引用</p>
<p><a href="">util.js</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//将各个大小类型划分各个方法,使他们相互独立,互不影响,各类型方法负责各自的逻辑算法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//对应类型的数据计算----策略类</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> fileSize = &#123;</span><br><span class="line">  <span class="string">&#x27;B&#x27;</span>: <span class="function"><span class="keyword">function</span>(<span class="params">size</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">return</span> size + <span class="string">&#x27;B&#x27;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">&#x27;KB&#x27;</span>: <span class="function"><span class="keyword">function</span>(<span class="params">size</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">let</span> sizeVal = size / <span class="number">1024</span></span><br><span class="line">      <span class="keyword">if</span>(size % <span class="number">1024</span>)&#123;</span><br><span class="line">        sizeVal = sizeVal.toFixed(<span class="number">2</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> sizeVal + <span class="string">&#x27;KB&#x27;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">&#x27;M&#x27;</span>: <span class="function"><span class="keyword">function</span>(<span class="params">size</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">let</span> sizeVal = size / <span class="built_in">Math</span>.pow(<span class="number">1024</span>,<span class="number">2</span>)</span><br><span class="line">      <span class="keyword">if</span>(size % <span class="number">1024</span>)&#123;</span><br><span class="line">        sizeVal = sizeVal.toFixed(<span class="number">2</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> sizeVal + <span class="string">&quot;M&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">&#x27;G&#x27;</span>: <span class="function"><span class="keyword">function</span>(<span class="params">size</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> sizeVal = size / <span class="built_in">Math</span>.pow(<span class="number">1024</span>,<span class="number">3</span>)</span><br><span class="line">    <span class="keyword">if</span>(size % <span class="number">1024</span>)&#123;</span><br><span class="line">      sizeVal = sizeVal.toFixed(<span class="number">2</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sizeVal + <span class="string">&quot;G&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">&quot;false&quot;</span>: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;-&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//类型判断</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">sizeType</span>(<span class="params">size</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> type,</span><br><span class="line">        B = <span class="number">1024</span>,</span><br><span class="line">        KB = <span class="built_in">Math</span>.pow(B,<span class="number">2</span>), <span class="comment">//1024KB</span></span><br><span class="line">        M = <span class="built_in">Math</span>.pow(B,<span class="number">3</span>), <span class="comment">// 1024M</span></span><br><span class="line">        G = <span class="built_in">Math</span>.pow(B,<span class="number">4</span>)  <span class="comment">// 1024G</span></span><br><span class="line">    <span class="keyword">switch</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">      <span class="keyword">case</span> size &gt; <span class="number">0</span> &amp;&amp; size &lt; B: type = <span class="string">&#x27;B&#x27;</span>;<span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> size &gt; <span class="number">0</span> &amp;&amp; size &lt; KB: type = <span class="string">&#x27;KB&#x27;</span>;<span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> size &gt; <span class="number">0</span> &amp;&amp; size &lt; M: type = <span class="string">&#x27;M&#x27;</span>;<span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> size &gt; <span class="number">0</span> &amp;&amp; size &lt; G: type = <span class="string">&#x27;G&#x27;</span>;<span class="keyword">break</span></span><br><span class="line">      <span class="keyword">default</span>: type = <span class="string">&#x27;false&#x27;</span>;<span class="keyword">break</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> type</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//环境类</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">fileSizeFilter</span>(<span class="params">size,unitType</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> type = unitType || sizeType(size)</span><br><span class="line">  <span class="keyword">return</span> fileSize[type](size)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><font color="#dd0000">逻辑清晰,易于扩展,提高可读性和可复用性</font></p>
<h2 id="多态的体现："><a href="#多态的体现：" class="headerlink" title="多态的体现："></a><strong>多态的体现：</strong></h2><p>当一个我们对这些数据发出对应单位的换算的请求的时候，返回计算的不同结果，这正是<font color="#dd0000">多态的体现</font></p>
<p>回看定义：</p>
<p>1.将一系列算法封装在一个策略类</p>
<p>2.达到<font color="#dd0000">‘’相互替换‘’</font>的目的：替换环境类Context中当前保存的策略对象，便能得到不同的计算结果</p>
<h2 id="策略模式的例子："><a href="#策略模式的例子：" class="headerlink" title="策略模式的例子："></a>策略模式的例子：</h2><p><font color="#dd0000">缓动动画：</font></p>
<p>缓动动画的实现也是同上原理,就是将各种上下左右运动的算法都封装在一个策略类里面,然后通过一个环境类传入一个请求,在策略类中调用对应的算法</p>
<p><font color="#dd0000">表单校验：</font></p>
<p>表单校验这个就比较贴近我们的业务的</p>
<p>我们将表单校验的算法都封装在一个<font color="#dd0000">策略类</font>里面：如：<font color="#dd0000">为空的校验，输入长度校验，格式校验的算法等等</font>，,然后通过一个环境类传入一个请求,在策略类中调用对应的算法</p>
<p>将这部分表单校验代码放进我们的工具类里面，就可以在程序的其他地方复用了，从而提高我们代码的可复用性</p>
<h2 id="策略模式的优缺点"><a href="#策略模式的优缺点" class="headerlink" title="策略模式的优缺点:"></a>策略模式的优缺点:</h2><p><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/3e4f8047e3114eb38da059b2e8d593d7.png" alt="策略对比改造前后"></p>
<p><font color="#dd0000">优点：</font></p>
<ol>
<li>避免多重条件语句的判断</li>
<li>易于切换，易于理解，易于扩展</li>
<li>提高代码的可复用性</li>
</ol>
<p><font color="#dd0000">缺点（问题不大）：</font> 增加许多策略类或者策略对象</p>
<p>定义回顾：<font color="#dd0000">定义一系列的算法，把他们封装起来，并且使他们可以相互替换</font></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">mozihao</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://mo_zi_hao.gitee.io/blog/posts/7457/">https://mo_zi_hao.gitee.io/blog/posts/7457/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://mo_zi_hao.gitee.io/blog" target="_blank">mozihao</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/">策略模式</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/0.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/posts/58992/"><img class="prev-cover" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">vue源码分析-准备工作</div></div></a></div><div class="next-post pull-right"><a href="/blog/posts/19482/"><img class="next-cover" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/0.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">设计模式-单例模式</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC008.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">mozihao</div><div class="author-info__description">if you risk nothing,then you risk anthing</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">24</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/mo_zi_hao"><i class="iconfont icon-gitee-fill-round"></i><span>我的Gitee</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/mo_zi_hao" target="_blank" title="Gitee"><i class="fab iconfont icon-gitee-fill-round"></i></a><a class="social-icon" href="https://github.com/mmCrazy" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/xiaomohhh?spm=1001.2101.3001.5343" target="_blank" title="CSDN"><i class="fab iconfont icon-csdn"></i></a><a class="social-icon" href="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/qrcode_for_gh_d35478eda980_430.jpg" target="_blank" title="公众号"><i class="fab iconfont icon-weixingongzhonghao"></i></a><a class="social-icon" href="mailto:747304031@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">如文章中有哪些错漏，欢迎各位前端的大佬与我交流并指正，谢谢!!</br>邮箱：747304031@qq.com</br>公众号：一起写前端bug</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.</span> <span class="toc-text">策略模式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9C%9F%E4%BA%BA%E7%9C%9F%E4%BA%8B%EF%BC%9A%E5%A4%A7%E5%9E%8B%E8%BD%A6%E7%A5%B8%E7%8E%B0%E5%9C%BA"><span class="toc-number">1.1.</span> <span class="toc-text">真人真事：大型车祸现场</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F%E9%87%8D%E6%9E%84%E4%BB%A3%E7%A0%81%EF%BC%9A"><span class="toc-number">1.1.1.</span> <span class="toc-text">策略模式重构代码：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%BB%E8%BE%91%E6%8B%86%E5%88%86%EF%BC%9A"><span class="toc-number">1.1.1.1.</span> <span class="toc-text">逻辑拆分：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E4%B8%AA%E5%9F%BA%E4%BA%8E%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%A8%8B%E5%BA%8F%E8%87%B3%E5%B0%91%E7%94%B1%E4%B8%A4%E9%83%A8%E5%88%86%E7%BB%84%E6%88%90%EF%BC%9A"><span class="toc-number">1.1.1.2.</span> <span class="toc-text">一个基于策略模式的程序至少由两部分组成：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E7%9A%84%E4%BD%93%E7%8E%B0%EF%BC%9A"><span class="toc-number">1.2.</span> <span class="toc-text">多态的体现：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BE%8B%E5%AD%90%EF%BC%9A"><span class="toc-number">1.3.</span> <span class="toc-text">策略模式的例子：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="toc-number">1.4.</span> <span class="toc-text">策略模式的优缺点:</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/1/" title="无题"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="无题"/></a><div class="content"><a class="title" href="/blog/posts/1/" title="无题">无题</a><time datetime="2022-06-05T05:20:17.974Z" title="发表于 2022-06-05 13:20:17">2022-06-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/36549/" title="编写可维护的JavaScript (代码习惯)"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="编写可维护的JavaScript (代码习惯)"/></a><div class="content"><a class="title" href="/blog/posts/36549/" title="编写可维护的JavaScript (代码习惯)">编写可维护的JavaScript (代码习惯)</a><time datetime="2022-03-19T03:12:42.624Z" title="发表于 2022-03-19 11:12:42">2022-03-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/23125/" title="gitlab-cicd"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="gitlab-cicd"/></a><div class="content"><a class="title" href="/blog/posts/23125/" title="gitlab-cicd">gitlab-cicd</a><time datetime="2021-12-20T14:00:59.661Z" title="发表于 2021-12-20 22:00:59">2021-12-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/449/" title="前端js基础"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/26&amp;gp=0.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="前端js基础"/></a><div class="content"><a class="title" href="/blog/posts/449/" title="前端js基础">前端js基础</a><time datetime="2021-08-29T15:22:14.600Z" title="发表于 2021-08-29 23:22:14">2021-08-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/35506/" title="微信小程序"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/1234.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="微信小程序"/></a><div class="content"><a class="title" href="/blog/posts/35506/" title="微信小程序">微信小程序</a><time datetime="2021-08-29T15:22:14.600Z" title="发表于 2021-08-29 23:22:14">2021-08-29</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By mozihao</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/local-search.js"></script><div class="js-pjax"></div><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>